package lv.solcraft.replication.client.filtering;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.sql.DataSource;

import lv.solcraft.replication.client.ClientConfig;
import lv.solcraft.replication.common.OperDTO;

import org.apache.commons.io.FileUtils;
import org.python.util.PythonInterpreter;
import org.springframework.util.Assert;

public class OperFilterImpl implements OperFilter {

    private PythonInterpreter python;

    private ClientConfig client;

    private DataSource dataSource;

    public void init() throws IOException {
        String tmpDir = System.getProperty("java.io.tmpdir");
        Assert.hasText(tmpDir, "Tmp dir is empty!");
        Properties props = new Properties();
        File jythonCacheDir = new File(tmpDir, "jythoncache");
        if (jythonCacheDir.exists())
            FileUtils.deleteDirectory(jythonCacheDir);
        props.setProperty("python.cachedir", jythonCacheDir.getAbsolutePath());
        PythonInterpreter.initialize(System.getProperties(), props, new String[] { "" });
        python = new PythonInterpreter();
    }

    public void execute(List<OperDTO> opers) {

        if (client.getSettings().getFilter() == null || "".equals(client.getSettings().getFilter().trim())) {
            return;
        }

        // create filter opers objects only for required table operations
        List<OperFilterObject> filterOpers = new ArrayList<OperFilterObject>();
        for (OperDTO oper : opers) {
            if (client.getSettings().filterTable(oper.getTable())) {
                OperFilterObject f = new OperFilterObject(dataSource, oper);
                filterOpers.add(f);
            }

        }

        // execute jython script
        if (!filterOpers.isEmpty()) {
            python.set("opers", filterOpers);
            python.set("site", client.getSiteId());
            String script = client.getSettings().getFilter();
            python.exec(script);
        }

    }

    public ClientConfig getClient() {
        return client;
    }

    public void setClient(ClientConfig client) {
        this.client = client;
    }

    public DataSource getDataSource() {
        return dataSource;
    }

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

}
